<?php

namespace app\mos\controller;

use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardLeaduser;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardRankUserLog;
use app\common\model\CardStore;
use app\common\model\CardUserFee;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserUpdate;
use app\common\model\MerchantContent;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\validate\LoginUsers;
use app\index\controller\Wxcard;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardlist extends Mobilebase
{



    //我的卡券  查询所有属于该openid的会员卡
    /*
     * $card_id
     */
    public function mecard()
    {
        $arr = request()->param();
        $this->_init();
        if (isset($arr['encrypt_code'])) {
            $this->getusercode($arr);
        }
        $appid = $this->getappid($arr['card_id']);
        $arr['openid'] = Session::get($appid . '_openid');
        $CardMember = new CardMember();
        $this->assign('card', $arr);
        $is_mecard = $CardMember->where('card_id', $arr['card_id'])->value('is_mecard');
        if ($is_mecard == 1) {
            return $this->fetch();
        } else {
            return $this->fetch('off');
        }

    }


    public function getmecard(){
        $param = request()->post();
        //我的会员卡
        $CardUserGet = new CardUserGet();
        //我的券
        $maps['openid'] = $param['openid'];
        $maps['have'] = 1;
        $maps['is_out'] = 0;
        $maps['card_type'] = array('neq', 'MEMBER_CARD');
        $maps['statu'] = ['neq', 2];
        $cardlists = $CardUserGet->where($maps)->order('statu asc')->paginate(5);
        $cardcount = $CardUserGet->where($maps)->count();
        $cardlist = [];
        $i = 0;
        foreach ($cardlists as $k=>$v){
            $cards = filemegetcard($v['card_id'],$v['code'],$v['create_time']);

            if ($cards['result'] == 1) {
                $cardlist[$i]['card_id'] = $v['card_id'];
                $cardlist[$i]['card_type'] = getcardtype($v['card_type']);
                $cardlist[$i]['code'] = $v['code'];
                $cardlist[$i]['card_logo'] = $cards['cards']['logo_url'];
                $cardlist[$i]['card_title'] = $cards['cards']['title'];
                $cardlist[$i]['brand_name'] = $cards['cards']['brand_name'];
                $cardlist[$i]['out_time'] = filtergqcards($v['card_id'],strtotime($v['create_time']));
                $i = $i+1;
            }else{
                $CardUserGet->save(['is_out'=>1],['id'=>$v['id']]);
            }
        }
        if ($cardlist){
            $data['code'] = 0;
            $data['message'] = 'SUCCESS';
            $data['data'] = $cardlist;
            $data['count'] = $cardcount;
            $data['page_num'] = ceil($cardcount / 5);
            $data['page'] = $param['page'];
        } else {
            $data['code'] = 0;
            $data['data'] = '';
            $data['message'] = 'error';
        }
        return json($data);
    }

    //已使用卡券列表
    public function alusedcardlist(Request $request){
        if ($request->isAjax()){
            $param = request()->post();
            //我的会员卡
            $CardUserGet = new CardUserGet();
            //我的券
            $maps['a.openid'] = $param['openid'];
//            $maps['have'] = 1;
            $maps['a.card_type'] = array('neq', 'MEMBER_CARD');
            $maps['a.statu'] = 2;
            $cardlists = $CardUserGet->alias('a')
                ->join('wn_card_general b', 'a.card_id=b.card_id', 'left')
                ->join('wn_card_consume c', 'a.code=c.code', 'left')
                ->where($maps)->order('c.create_time desc')
                ->field('a.card_id,a.code,a.end_time,a.update_time,a.card_type,b.logo_url,b.title,b.brand_name,c.create_time')->paginate(5);
            $cardcount = $CardUserGet->alias('a')->where($maps)->count();
            $cardlist = [];
            $i = 0;
            foreach ($cardlists as $k=>$v){
                $cardlist[$i]['card_id'] = $v['card_id'];
                $cardlist[$i]['card_type'] = getcardtype($v['card_type']);
                $cardlist[$i]['code'] = $v['code'];
                $cardlist[$i]['card_logo'] = $v['logo_url'];
                $cardlist[$i]['card_title'] = $v['title'];
                $cardlist[$i]['brand_name'] = $v['brand_name'];
                $cardlist[$i]['out_time'] = $v['create_time'];
                $i = $i+1;
            }
            if ($cardlist){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $cardlist;
                $data['count'] = $cardcount;
                $data['page_num'] = ceil($cardcount / 5);
                $data['page'] = $param['page'];
            } else {
                $data['code'] = 0;
                $data['data'] = '';
                $data['message'] = 'error';
            }
            return json($data);
        }else{

            $param = request()->param();
            $this->_init();
            $userinfo = $this->getuserinfo($param,1);
            $this->assign('userinfo',$userinfo);
            return $this->fetch();
        }
    }

    //已过期卡券列表
    public function alendcardlist(Request $request){
        if ($request->isAjax()){
            $param = request()->post();
            //我的会员卡
            $CardUserGet = new CardUserGet();
            //我的券
            $maps['a.openid'] = $param['openid'];
            $maps['a.have'] = 1;
            $maps['a.end_time'] = array('lt', time());
            $maps['a.card_type'] = array('neq', 'MEMBER_CARD');
//            $maps['is_out'] = 1;
            $cardlists = $CardUserGet->alias('a')
                ->join('wn_card_general b', 'a.card_id=b.card_id', 'left')->where($maps)->order('a.end_time desc')
                ->field('a.card_id,a.code,a.end_time,a.card_type,b.logo_url,b.title,b.brand_name')->paginate(5);
            $cardcount = $CardUserGet->alias('a')->where($maps)->count();
            $cardlist = [];
            $i = 0;
            foreach ($cardlists as $k=>$v){
                $cardlist[$i]['card_id'] = $v['card_id'];
                $cardlist[$i]['card_type'] = getcardtype($v['card_type']);
                $cardlist[$i]['code'] = $v['code'];
                $cardlist[$i]['card_logo'] = $v['logo_url'];
                $cardlist[$i]['card_title'] = $v['title'];
                $cardlist[$i]['brand_name'] = $v['brand_name'];
                $cardlist[$i]['out_time'] = date('Y-m-d',$v['end_time']);
                $i = $i+1;
            }
            if ($cardlist){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $cardlist;
                $data['count'] = $cardcount;
                $data['page_num'] = ceil($cardcount / 5);
                $data['page'] = $param['page'];
            } else {
                $data['code'] = 0;
                $data['data'] = '';
                $data['message'] = 'error';
            }
            return json($data);
        }else{
            $param = request()->param();
            $this->_init();
            $userinfo = $this->getuserinfo($param,1);
            $this->assign('userinfo',$userinfo);
            return $this->fetch();
        }
    }


    //AJax打开卡
    /*
     * $arr['card_id'] , $arr['url']
     *
     */
    public function getopencard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $card_id = $arr['card_id'];
            $appid = $this->getappid($card_id);
            $openid = Session::get($appid.'_openid');
            $CradUserGet = new CardUserGet();
            $map['openid'] = $openid;
            $map['card_id'] = $card_id;
            $map['code'] = $arr['cardcode'];
            $map['have'] = 1;
            $map['statu'] = 0;
            $info = $CradUserGet->where(['card_id' => $card_id, 'openid' => $openid,'code' =>  $arr['cardcode'], 'have' => '1', 'statu' => 0])->find();

            if ($info) {
                $url = $arr['url'];
                $options = $this->options($card_id);
                $weObj = new Wxobjopen($options);

                $jssdk = $weObj->getJsSign($url);
                //输出内容
                $card['jssdk']['debug'] = true;
                $card['jssdk']['appId'] = $jssdk['appId'];
//                $card['jssdk']['api_ticket'] = $jssdk['ticket'];
//                $card['jssdk']['url'] = $jssdk['url'];
                $card['jssdk']['timestamp'] = $jssdk['timestamp'];
                $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
                $card['jssdk']['signature'] = $jssdk['signature'];
                $card['jssdk']['jsApiList'] = ['hideAllNonBaseMenuItem','openCard'];
                $card['card']['cardId'] = $card_id;
                $card['card']['code'] = $info['code'];
                return json($card);
            } else {
                $data['code'] =  9001;
                $data['msg'] = '没有此卡，请先领取！';
                return json($data);
            }
        }
    }

    //Ajax打开领取
    /*
     * $arr['card_id']
     */
    public function getaddcard(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $options = $this->options($arr['card_id']);
            //发放
            $arrs['card_id'] = $arr['card_id'];
            $appid = $this->getappid($arr['card_id']);
            $arrs['openid'] = Session::get($appid.'_openid');
            $weObj = new Wxobjopen($options);
            $jssdk = $weObj->get_card_JsSign($url);
            //输出内容
            $card['card'] = $this->put($arrs);
            $card['jssdk']['debug'] = false;
            $card['jssdk']['api_ticket'] = $jssdk['ticket'];
            $card['jssdk']['url'] = $jssdk['url'];
            $card['jssdk']['appId'] = $jssdk['appId'];
            $card['jssdk']['timestamp'] = $jssdk['timestamp'];
            $card['jssdk']['nonceStr'] = $jssdk['nonceStr'];
            $card['jssdk']['signature'] = $jssdk['signature'];
            $card['jssdk']['jsApiList'] = ['penCard','addCard'];
            return json($card);
        }
    }

    //发放卡列表
    /*
     * $arr['openid'] / $arr['give'] /
     *
     */
    public function addcardlist()
    {
        $this->_init();
        $arr = request()->param();
        if (isset($arr['openid']) && isset($arr['give'])) {
            $appid = $this->getappid($arr['card_id']);
            if ($arr['openid'] == Session::get($appid.'_openid')) {
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('zs_card_id');
                $cardlist = explode(',', $card_id);
                foreach ($cardlist as $k => $v) {
                    if (filteroffcard($v) == true) {
                        $options = $this->options($v);
                        $arrs['card_id'] = $v;
                        $arrs['openid'] = $arr['openid'];
                        $card[$k] = $this->putlist($arrs);
                    }
                }
                if(isset($options)){
                    $weObj = new Wxobjopen($options);
                    $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                    $jssdk = $weObj->getJsSign($url);
                    $this->assign('card', json_encode($card));
                    $this->assign('jssdk', $jssdk);
                    return $this->fetch();
                }
                else{
                    $this->error("该卡券已过期");
                }
            }else{
                $CardCzgive = new CardCzgive();
                $card_id = $CardCzgive->where('id', $arr['give'])->value('card_id');
                $this->redirect('Carduser/weboff', ['card_id' => $card_id]);
            }
        }
    }

    //批量投放
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function putlist($arr){
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $res['cardId'] = $arr['card_id'];
        $res['cardExt'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr);
        return $res;
    }

    //投放卡
    /*
     * $arr['openid'] / $arr['card_id']
     */
    private function put($arr)
    {
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $noncestr = $weObj->generateNonceStr();
        $outer_str = 'CardCenter';
        $res['card_id'] = $arr['card_id'];
        $res['addcard'] = $weObj->wxAddCard($arr['openid'], $arr['card_id'], $noncestr,$outer_str);
        return $res;

    }

    //获取该门店所属商户的所有下属门店
    /*
     * $mid
     */
    private function getmidlist($mid){
        $Merchant = new Merchant();
        $top_mid = $Merchant->where('id',$mid)->value('top_mid');
        $midlist = $Merchant->where(['top_mid' => $top_mid])->field('id')->select();
        $smid=[];
        foreach ($midlist as $k => $v) {
            $smid[] = $v['id'];
        }
        $mids = implode(',', $smid);
        return $mids;
    }

    /* 获取创建该卡券的门店id
     *
     * $card_id
     *
     */
//    private function getmid($card_id)
//    {
//        $CardMember = new CardMember();
//        $CardGeneral = new CardGeneral();
//        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
//        if (empty($top_mid)) {
//            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
//            return $top_mid;
//        } else {
//            return $top_mid;
//        }
//    }



    //分享jssdk
    /*
     * $card_id
     * 
     */
    private function getsharejssdk($arr){
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $options = $this->options($arr);
        //分享
        $weObj = new Wxobjopen($options);
        $jssdk = $weObj->getJsSign($url);
        $wxJsSdk = [
            'debug' => false,
            'appId' => $jssdk['appId'],
            'timestamp' =>$jssdk['timestamp'],
            'nonceStr' => $jssdk['nonceStr'],
            'signature' => $jssdk['signature'],
            'jsApiList' => [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareQZone',
                'closeWindow',
                'hideAllNonBaseMenuItem',
            ]
        ];
        return $wxJsSdk;
    }
    public function test(){
        echo request()->domain();
        exit();
        $s=getgivecardnew('[{"zs_card_id":"pCVCLv0Z2UNmnrRcoC2bamHpj0EY","zs_no":"2"}]',0);
        var_dump($s);
    }


}
